<template>
	<div>
		<div class="content_search_box main-box">
			<el-form  ref="searchFactor" :model="searchFactor" label-width="80px">
				<div style="display:flex">
					<el-form-item label="设备名称:">
						<el-select v-model='searchFactor.deviceIndex'  @change="queryPointName()" filterable clearable>
                            <el-option v-for="(item,index) in deviceList" :key="index" :label="item.deviceName" :value="index">
                            </el-option>
                        </el-select>
					</el-form-item>
					<el-form-item :label="$t('spotMonitor.pointName')+':'">
						<el-select class= 'wd100' v-model='searchFactor.pointIndexs' @change="changePoint()" :collapse-tags='true' multiple  filterable clearable>
							<el-option v-for="(item,index) in pointList" :key="index" :label="item.pointName+'('+item.manuId+')'" :value="index">
							</el-option>
						</el-select>	
					</el-form-item>
				</div>
				<div class="mt5" style="display:flex">
					<el-form-item label="日期范围:">
						<datatime :pointIds="searchFactor.deviceIds" :time="searchFactor.modify_start_time" dataType="origin" @changeTime="(time)=>{searchFactor.modify_start_time = time}" :placeholderText="$t('spotMonitor.startDate')" style="width:180px" />
					</el-form-item>
					<el-form-item label-width="10px">
						<datatime :pointIds="searchFactor.deviceIds" :time="searchFactor.modify_end_time" dataType="origin" @changeTime="(time)=>{searchFactor.modify_end_time = time}"  :placeholderText="$t('spotMonitor.endDate')" style="width:180px" />
					</el-form-item>
					<el-form-item label="筛选条件:">
						<el-select class="min-width" :popper-append-to-body='false' v-model="searchFactor.phy" placeholder="物理量" clearable>
							<el-option v-for="(item,index) in titleList" :key="index" :label="item.phyName" :value="item.lastIdx"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item v-if="searchFactor.phy" label-width="10px">
						<el-select class="min-width" :popper-append-to-body='false' v-model="searchFactor.symbol" placeholder="符号" clearable>
							<el-option v-for="(item,index) in symbolList" :key="index" :label="item.name" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item v-if="searchFactor.symbol" label-width="10px">
						<el-input v-model="searchFactor.startValue" style="width:55px"></el-input>
						<el-input v-if="['-', '!-'].includes(searchFactor.symbol)" v-model="searchFactor.endValue" style="width:55px"></el-input>
					</el-form-item>
					<el-form-item label-width="10px">
						<el-button type="primary" icon="el-icon-search" @click.native = "queryData()">{{$t("common.search")}}</el-button>
						<el-button v-if="multipleSelection.length" type="danger" icon="el-icon-delete"  @click.native = "batchDelete()">删除勾选项</el-button>
						<el-button type="danger" icon="el-icon-delete"  @click.native = "deleteAll()">删除全部</el-button>
					</el-form-item>
				</div>
			</el-form>
		</div>
		<div v-if="gridList.length">
			<el-table class="mt10" height="calc(100vh - 280px)" 
			@selection-change="handleSelectionChange"
			:data="gridList" stripe>
				<el-table-column type="selection" width="45"></el-table-column>
				<el-table-column prop="pointName" :label="$t('girdData.pointName')">
					<template slot-scope="scope">
						{{getPointNameByDeviceId(scope.row.data_id)}}
					</template>
				</el-table-column>
				<el-table-column prop="data_time" :label="$t('girdData.time')"  sortable></el-table-column>
				<el-table-column prop="data" v-for="(item,idx) in titleList" :key="idx"> 
					<template slot="header" slot-scope="scope" >
						{{item.phyName}}
					</template>
					<template  slot-scope="scope">
						<span >{{(scope.row['data'+item.lastIdx]==undefined?'':scope.row['data'+item.lastIdx])+(scope.row['unit'+item.lastIdx]||"")}}</span>
					</template>
				</el-table-column>
				<el-table-column  :label="this.$t('common.right')">
					<template  slot-scope="scope">
					<el-button type="text" size="mini" icon="el-icon-delete"  @click.native.prevent="deletePoint([{_id:scope.row._id}])">{{$t('common.delete')}}</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination class="page_sub" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
			:page-sizes="[60,120,200,300,400,500]"
			:page-size="size"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total">
			</el-pagination>
		</div>
	 </div>
</template>
<script>
import { util } from "@/utils/common.js";
import { mapGetters } from 'vuex'
export default {
    data(){
        return{
			collapseTag:true,
	    	searchFactor:{
	    		deviceName:'',
                deviceIndex:'',
                projectId:'',
                pointIndexs:[],
                pointIds:[],
                deviceIds:[],
                phy:'',
                modify_start_time:'',
                modify_end_time:'',
                symbol:'>='
	    	},
			symbolList:[
				{name:"大于等于",value:">="},
				{name:"大于",value:">"},
				{name:"小于",value:"<"},
				{name:"小于等于",value:"<="},
				{name:"介于",value:"-"},
				{name:"不介于",value:"!-"},
				{name:"等于",value:"=="},
				{name:"不等于",value:"!="}
			],
	    	phyList:[],
	    	pointList:[],
	    	positionList:[],
	    	allPoints:[],
	    	allFactors:[],
			deviceList:[],
			gridList:[],
			allDataList:[],
			titleList:[],
			multipleSelection:[],
			page:1,
			size:60,
			total:0,
        }
    },
	computed: {
	    // 使用对象展开运算符将 getter 混入 computed 对象中
	    ...mapGetters([
	      'projectInfo'
	    ])
  	},
    mounted() {
		this.initDeviceList();
	},
	watch:{
		projectInfo(){		  
			this.initData();
			this.searchFactor.projectId = this.projectInfo.id;
			this.initDeviceList();
		}
	},
	methods:{
		//初始化数据
		initData(){
			this.searchFactor = {
				projectId:'',
				pointIds:[],
				deviceIds:[],
				phy:'',
				modify_start_time:'',
				modify_end_time:''
			}
			this.pointList = [];
			this.deviceList = []
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		handleSizeChange(size){
			this.size = size;
			this.page = 1;
			this.handleCurrentChange(1)
		},
		handleCurrentChange(page){
			this.page = page;
			this.size = this.size;
			this.gridList = this.allDataList.slice((this.page-1)*this.size,this.page*this.size)
		},
		getPointNameByDeviceId(data_id){
			let point = this.pointList.find(item=>item.deviceId == data_id)
			return point.pointName+"("+point.manuId+")"
		},
		//初始化项目类型占比
        initDeviceList(){
            this.$httpProj.get("/device/device/getDeviceNames").then(data=>{
                this.deviceList = data.data||[];
                if(this.deviceList[0]){
                    this.searchFactor.deviceIndex = 0;
                    this.queryPointName();
                }
            })
        },
        //查询测点名称
        queryPointName(){
            let device = this.deviceList[this.searchFactor.deviceIndex]||{}
            this.searchFactor.deviceName = device.deviceName
            this.searchFactor.pointIndexs = [];
            this.pointList = [];
            this.$httpProj.get("/point/point/getPointNamesByDeviceName?deviceName="+this.searchFactor.deviceName).then(data=>{
                this.searchFactor.deviceIds = []
                data.data.forEach(item =>{
                    item.id = item.pointId;
                })
                this.pointList = data.data;
                if(data.data[0]){
                    this.searchFactor.pointIndexs = [0];
                    this.changePoint()
                }
            })
        },
        changePoint(){
            this.searchFactor.pointIds = []
            this.searchFactor.deviceIds = []
            this.selectPointList = [];
            this.searchFactor.pointIndexs.forEach(item=>{
                let point = this.pointList[item]
                this.selectPointList.push(point)
                this.searchFactor.pointIds.push(point.pointId)
                this.searchFactor.deviceIds.push(point.deviceId);
            })
            this.queryData()
        },
		queryData(page){
			 this.page = page||1;
			let searchFactor = this.searchFactor,dateTime = ""
			let startTime = searchFactor.modify_start_time||"",
				endTime = searchFactor.modify_end_time||""
			if(startTime){
				startTime = startTime.split(" ").length>1?startTime.replace(' ','T'):(startTime+"T00:00:00")
			}else{
				startTime = '*'
			}
			if(endTime){
				endTime = endTime.split(" ").length>1?endTime.replace(' ','T'):(endTime+"T23:59:59")
			}else{
				endTime = '*'
			}
			dateTime = " AND data_time:["+startTime+" TO "+endTime+"]"
			if(this.searchFactor.deviceIds.length == 0){
				this.gridList = []
				return
			}
			let query="("
			this.searchFactor.deviceIds.forEach((item,index)=>{
				if(index==0){
					query+='data_id:'+item
				}else{
					query+=' OR data_id:'+item
				}
			})
			query+=")"+dateTime
			let sendData = {
				query:query,
				pageSize:100000,//写死查询数量 ssh
				pageNum:1
			}
			this.$httpEs.post('/line/queryLineTableResult?cancelRequest=true',sendData).then(data=>{
				let datas = data.data.datas;
				this.initTitleList(datas)
				this.initGridList(datas)
				
			})
		},
		initTitleList(datas){
			let titleList  = [];
			datas.forEach(item=>{
				Object.keys(item).forEach(it=>{
					let lastIdx = it.slice(-1)
					if(util.phyList.includes(it)&&titleList.findIndex(i=>{return i.lastIdx == lastIdx})==-1){
						titleList.push({lastIdx:lastIdx,phyName:item['phyName'+lastIdx],unit:item['unit'+lastIdx]})
					}
				})
			})
			titleList = titleList.sort((a,b)=>{return a.lastIdx-b.lastIdx})
			this.titleList = [];
			this.$nextTick(()=>{
				this.titleList = titleList
			})
			this.searchFactor.phy = this.searchFactor.phy||titleList[0]?.lastIdx;
		},
		initGridList(datas){
			let searchFactor = this.searchFactor;
			let lastIdx = searchFactor.phy
			this.allDataList =  datas
			if(searchFactor.startValue&&(searchFactor.endValue||searchFactor.endValue == 0)){
				if(searchFactor.symbol == '-'){
					this.allDataList =  datas.filter(item=>item['data'+lastIdx]>(searchFactor.startValue)&&item['data'+lastIdx]<searchFactor.endValue)
				}else if(searchFactor.symbol == '!-'){
					this.allDataList =  datas.filter(item=>item['data'+lastIdx]<(searchFactor.startValue)||item['data'+lastIdx]>searchFactor.endValue)
				}
			}else if(searchFactor.startValue){
				this.allDataList =  datas.filter(item=>eval(item['data'+lastIdx]+searchFactor.symbol+searchFactor.startValue))
			}
			this.handleCurrentChange(1)
			this.total = this.allDataList.length
		},
		batchDelete(){
			let ids = this.multipleSelection.map(item=> {
				return {_id:item._id,data_id:item.data_id,data_time:item.data_time}
			})
			this.deletePoint(ids)
		},
		deleteAll(){
			let ids = this.allDataList.map(item=> {
				return {_id:item._id,data_id:item.data_id,data_time:item.data_time}
			})
			this.deletePoint(ids)
		},
		deletePoint(ids){
			this.$confirm(this.$t('common.confirmDel'), this.$t('common.tip'), {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			}).then(() => {
				this.$httpEs.post("/line/deleteIndexById",ids).then( res=> {
					this.$message({
						message: this.$t('common.delSuccess'),
						type: 'success'
					});
					// ES 查询会有延迟
					setTimeout(()=>{
						this.queryData()
					},600)
				})
			})
		},
	}
}
</script>